
#import "NHTWebViewControl.h"
#import <WebKit/WebKit.h>
#import <Masonry/Masonry.h>


//static NSString *const kTargetURL = @"https://m.dttrip.cn";

//static NSString *const kTargetURL = @"https://ct.ctrip.com/m/SingleSignOn/H5SignInfo?SsoData=QWNjZXNzVXNlcklkPW9ia19OSFFIJkVtcGxveWVlSWQ9bGl5YWRvbmcmU2lnbmF0dXJlPWVmOGVkNThhODZmMmEyYTQxMGU3MWMzMWQ4N2Q2NmVjJkluaXRQYWdlPUhvbWUmQXBwSWQ9TkhRSCZUb2tlbj02OTA0MjUxZDNkMTZiMGU0ZjE2YjZmNTE%3D";

//static NSString *const kTargetURL = @"https://m.qa.dttrip.cn/newapp/pages/common/facialRecognition/test";

static NSString *const kTargetURL = @"https://m.qa.dttrip.cn/newapp/pages/center/index";


@interface NHTWebViewControl () <WKUIDelegate, WKNavigationDelegate>

/// 加载进度
@property (nonatomic, strong) UIProgressView *progressView;

/// H5容器
@property (nonatomic, retain) WKWebView *wkWebView;

@end

@implementation NHTWebViewControl

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 进度条
    [self.view addSubview:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0.f);
        make.height.mas_equalTo(2.f);
    }];
    
    // WebView
    [self.view addSubview:self.wkWebView];
    [self.wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(90);
        make.left.right.bottom.mas_equalTo(self.view);
    }];
   
    [self loadWebViewContent];
    // 监听加载进度和标题
    [self.wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:nil];
    [self.wkWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
}

 

- (void)dealloc {
    [_wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    [_wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(title))];
}

#pragma mark - Private Methods

/// 加载 WebView 内容
- (void)loadWebViewContent {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:kTargetURL]];
    [self.wkWebView loadRequest:request];
}

 
 
#pragma mark - WKUIDelegate

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    decisionHandler(WKNavigationResponsePolicyAllow);
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [self.progressView setProgress:0.0f animated:NO];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [self.progressView setProgress:0.0f animated:NO];
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context {
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == _wkWebView) {
            self.progressView.progress = _wkWebView.estimatedProgress;
            if (_wkWebView.estimatedProgress >= 1.0f) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self.progressView.progress = 0;
                });
            }
        } else if ([keyPath isEqualToString:@"title"] && object == _wkWebView) {
            self.navigationItem.title = _wkWebView.title;
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    });
}

#pragma mark - Getters
 

- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectZero];
        _progressView.tintColor = [UIColor redColor];
        _progressView.trackTintColor = [UIColor clearColor];
    }
    return _progressView;
}

- (WKWebView *)wkWebView {
    if (!_wkWebView) {
        // 创建 WebView 配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        // 设置 User-Agent（用户代理字符串）
        // 作用：告诉服务器当前使用的浏览器类型和版本，某些 H5 服务可能根据 User-Agent 判断是否支持某些功能（如摄像头）
        // 这里设置为 Safari 的 User-Agent，以提高兼容性
        config.applicationNameForUserAgent = @"Version/16.6 Mobile/15E148 Safari/604.1";
        
        // 允许内联媒体播放
        // 作用：允许视频/音频在页面内播放，而不是全屏播放。对于人脸认证等场景很重要
        config.allowsInlineMediaPlayback = YES;
        
        // 设置需要用户交互才能播放的媒体类型
        // 作用：设置为 None 表示所有媒体都可以自动播放，无需用户交互。这对摄像头预览等功能很重要
        if (@available(iOS 10.0, *)) {
            config.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
        } else {
            // iOS 10 以下版本的设置方式
            config.requiresUserActionForMediaPlayback = NO;
        }
        
        // 创建偏好设置对象
        WKPreferences *preference = [[WKPreferences alloc] init];
        
        // 启用 JavaScript
        // 作用：允许页面执行 JavaScript 代码，现代 H5 页面基本都需要
        preference.javaScriptEnabled = YES;
        
        // 允许 JavaScript 自动打开窗口
        // 作用：允许 JavaScript 在不需要用户交互的情况下打开新窗口（如 window.open()）
        preference.javaScriptCanOpenWindowsAutomatically = YES;
        
//        // 允许加载非标准 URL scheme
//        [preference setValue:@(YES) forKey:@"allowFileAccessFromFileURLs"];
//
//        // 如果需要跨域访问，添加这个（注意：在较新系统版本中可能需要其他额外配置或考虑安全性问题）
//        [preference setValue:@(YES) forKey:@"allowUniversalAccessFromFileURLs"];
        
        // 将偏好设置应用到配置
        config.preferences = preference;
        
        
        // 创建用户内容控制器
        // 作用：管理用户脚本和消息处理，用于 Native 与 JavaScript 之间的通信
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        config.userContentController = wkUController;
        
        // 创建 WebView 实例
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        
        // 设置 UI 代理
        // 作用：处理 JavaScript 弹窗（alert、confirm、prompt）和权限请求等 UI 相关操作
        _wkWebView.UIDelegate = self;
        
        // 设置导航代理
        // 作用：处理页面加载、跳转、错误等导航相关事件
        _wkWebView.navigationDelegate = self;
        
        
        
        // 启用 Web Inspector（仅在 iOS 16.4+ 可用）
        // 作用：允许在 Safari 开发者工具中调试 WebView 中的页面
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130300 || \
    __IPHONE_OS_VERSION_MAX_ALLOWED >= 160400 || \
    __TV_OS_VERSION_MAX_ALLOWED >= 160400
        if (@available(macOS 13.3, iOS 16.4, tvOS 16.4, *)) {
            _wkWebView.inspectable = YES;
        }
#endif
        
        // 设置 ScrollView 的内容内边距调整行为
        // 作用：设置为 Never 表示不使用系统自动调整内容内边距，避免内容被状态栏/导航栏遮挡
        _wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    return _wkWebView;
}

@end
